/*
 * Copyright (c) 2016. 恒昌互联网运营中心.
 */
package com.credithc.eagleeye.agent.strategy;
import com.credithc.eagleeye.agent.bean.EagleEyeAgentConfig;
import com.credithc.eagleeye.agent.util.HttpClientUtil;
import com.credithc.eagleeye.util.FastJsonConvert;
import com.credithc.eagleeye.vo.RpcTraceInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2017年04月22日<br/>
 * 版 本：v1.0.0<br>
 * <p/>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
public class HttpEagleEyeAgent extends AbsEagleEyeAgent {
    private transient static final Logger logger = LoggerFactory.getLogger(HttpEagleEyeAgent.class);
    private static AtomicBoolean initialized = new AtomicBoolean(false);
    private String eagleApiUrl;
    public HttpEagleEyeAgent(EagleEyeAgentConfig eagleEyeAgentConfig) {
        super(eagleEyeAgentConfig);
        init();
    }
    private void init() {
        if (initialized.compareAndSet(false, true)) {
            logger.info("HttpEagleEyeAgent init starting...");
            String host = eagleEyeAgentConfig.getHttpHost();
            if (host == null || host.length() == 0) {
                throw new RuntimeException("HttpEagleEyeAgent error:http config host is blank!");
            }
            String port = eagleEyeAgentConfig.getHttpPort();
            if (port == null || port.length() == 0) {
                port = "8080";
                logger.info("HttpEagleEyeAgent port is blank,use default port:8080");
            }
            this.eagleApiUrl = String.format("http://%s:%s/eagleEyeApi/", host, port);
            logger.info("HttpEagleEyeAgent init finished,eagleApiUrl:" + eagleApiUrl);
        }
    }
    @Override
    public boolean doSend2EagleEye(final RpcTraceInfoVo rpcTraceInfoVo) {
        try {
            String result = HttpClientUtil.postJson(eagleApiUrl, FastJsonConvert.convertObjectToJSON(rpcTraceInfoVo), "UTF-8");
            logger.debug(String.format("send to eagleEye http traceId:%s,rpcId:%s", rpcTraceInfoVo.getTraceId(), rpcTraceInfoVo.getRpcId()));
            if (StringUtils.equals(result, "success")) {
                return true;
            }
        } catch (Exception ex) {
            logger.error(String.format("http方式发送鹰眼系统error:%s,traceId:%s,rpcId:%s", ex.getMessage(), rpcTraceInfoVo.getTraceId(), rpcTraceInfoVo.getRpcId()));
        }
        return false;
    }
}
